#include "b_tree.h"
#include "draw_tree.h"
#include "stdlib.h"
#include "string.h"

draw_tree_node *convert_b_tree_node(b_tree_node *node)
{
	int i;
	draw_tree_node *res = (draw_tree_node*)malloc(sizeof(draw_tree_node));
	res->key_num = node->num_key;
	res->pkey = (int*)malloc(sizeof(int)*node->num_key);
	memcpy(res->pkey,node->key_values,sizeof(int)*node->num_key);
	if (!node->bLeaf)
	{
		res->link_num = node->num_key + 1;
		res->pnode = (draw_tree_node**)malloc(sizeof(draw_tree_node*)*(node->num_key+1));
		for (i = 0;i<=node->num_key;i++)
		{
			res->pnode[i] = convert_b_tree_node(node->childs[i]);
		}
	}
	else
	{
		res->link_num = 0;
	}
	return res;
}

draw_tree *convert_b_tree(b_tree *tree)
{
	draw_tree* dtree = (draw_tree*)malloc(sizeof(draw_tree));
	dtree->root = convert_b_tree_node(tree->root);
	return dtree;
}

int get_width_b_tree(b_tree *tree)
{
	b_tree_node *node = tree->root;
	int depth = 0;
	while (!node->bLeaf)
	{
		depth += 1;
		node = node->childs[0];
	}
	depth ++;
	return depth *ONE_NODE_WIDTH;
}

void cal_height(b_tree_node *node,int *height)
{
	int i;
	if (node->bLeaf)
	{
		(*height) += node->num_key*2+1+ONE_NODE_LINE_GAP;
	}
	else
	{
		for (i = 0;i<=node->num_key;i++)
		{
			cal_height(node->childs[i],height);
		}
	}
}

int get_height_b_tree(b_tree *tree)
{
	int height = 0;
	cal_height(tree->root,&height);
	return height;
}

int main()
{
	FILE *file;
	b_tree *tree = b_tree_init();
	draw_tree *dtree;
	int height,width;
	int i;
	char *memory;
	for (i = 0;i<51;i++)
	{
		b_tree_insert(tree,i);
	}
	b_tree_insert(tree,i);
	b_tree_delete(tree,24);
	b_tree_delete(tree,4);
	b_tree_delete(tree,9);
	b_tree_delete(tree,0);
	b_tree_delete(tree,1);
	b_tree_delete(tree,2);
	b_tree_delete(tree,3);
	height = get_height_b_tree(tree) +5;
	width = get_width_b_tree(tree) + 2;
	memory = (char *)malloc(sizeof(char)*width*height);
	dtree = convert_b_tree(tree);
	file = fopen("draw.txt","w");
	draw_one_tree(file,dtree,memory,width,height);
	fclose(file);
	return 0;
}